<?php

namespace app\modules\admin\services;

use app\common\services\BaseService;
use app\components\pagination\Pagination;
use app\config\Constants;
use app\models\GoodsOrder;
use app\modules\admin\forms\order\AdjustForm;
use yii\helpers\Json;

class GoodsOrderService extends BaseService{

    /**
     * 搜索
     * @param $merchant_id
     * @param $order_no
     * @param $pay_method
     * @param $status
     * @param $pay_status
     * @param $is_adjust
     * @param $start_time
     * @param $end_time
     * @param $page
     * @param $pagesize
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($merchant_id,$order_no,$pay_method,$status,$pay_status,$is_adjust,$start_time,$end_time,&$page,$pagesize){
        $query = GoodsOrder::find()->asArray(true)
            ->orderBy(['order_id'=>SORT_DESC]);

        if(!empty($merchant_id)){
            $query->andWhere(['merchant_id'=>$merchant_id]);
        }
        if(!empty($order_no)){
            $query->andWhere(['like','order_no',$order_no]);
        }
        if(!empty($pay_method)){
            $query->andWhere(['pay_method'=>$pay_method]);
        }
        if(!empty($status)){
            $query->andWhere(['status'=>$status]);
        }
        if(!empty($pay_status)){
            $query->andWhere(['pay_status'=>$pay_status]);
        }
        if(!empty($is_adjust)){
            $query->andWhere(['is_adjust'=>$is_adjust]);
        }
        if(!empty($start_time)){
            $query->andWhere(['>=',"date_format(add_time,'%Y-%m-%d')",$start_time]);
        }
        if(!empty($end_time)){
            $query->andWhere(['<=',"date_format(add_time,'%Y-%m-%d')",$end_time]);
        }

        $page = new Pagination(['totalCount' => $query->count(), 'pageSize' => $pagesize]);
        $query->offset($page->getOffset());
        $query->limit($page->getLimit());
        $data = $query->all();

        foreach($data as $k=>$v){
            if($v['status'] == Constants::ORDER_ADJUST || $v['is_adjust'] == 2){
                $data[$k]['credentials'] = GoodsOrderCredentialService::getInfoById($v['order_id']);
            }
        }

        return $data;
    }

    /**
     * 获取信息
     * @param $merchant_id
     * @param $id
     * @return array|null
     */
    public static function getInfoById($merchant_id,$id){
        $model = GoodsOrder::find()
            ->asArray(true)
            ->andWhere(['merchant_id'=>$merchant_id,'order_id'=>$id])
            ->one();
        if(!$model){
            return null;
        }
        if($model['status'] == Constants::ORDER_ADJUST || $model['is_adjust'] == 2){
            $model['credentials'] = GoodsOrderCredentialService::getInfoById($merchant_id,$id);
        }

        return $model;
    }

    /**
     * 调单
     * @param AdjustForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\Exception
     * @throws \yii\db\StaleObjectException
     */
    public static function adjust(AdjustForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model =  GoodsOrder::findOne(['merchant_id'=>$form->merchant_id,'order_id'=>$form->order_id]);
        if(!$model){
            self::setError(\Yii::t("app",''));
            return false;
        }

        $org_goods_item = Json::decode($model->goods_item);
        $new_goods_item = [];
        $total_price = 0;
        foreach($form->goods_item as $k=>$v){
            $attr_price = 0;
            $goods = GoodsService::getInfoById($form->merchant_id,$v['goods_id']);
            if(!$goods){
                continue;
            }

            $new_goods =  [
                'goods_id'=>$goods['goods_id'],
                'thumbnail'=>$goods['thumbnail'],
                'goods_name'=>$goods['goods_name'],
                'weight'=>$goods['weight'],
                'new_count'=>$v['new_count'],
            ];

            if(isset($v['attr_ids'])){
                $attr_ids = $v['attr_ids'];
                sort($attr_ids);
                foreach($attr_ids as $vv){
                    $attr = GoodsAttributeService::search($vv,$v['goods_id'],null);
                    if(!$attr){
                        continue;
                    }
                    $attr_price += $attr[0]['attr_price'];
                    $new_goods['attr_ids'][] = $vv;
                    $new_goods['attr_names'][] = $attr[0]['attr_value'];
                }
            }

            $total_price += (($goods['price'] + $attr_price) * $v['new_count']);
            $new_goods['price'] = $goods['price'] + $attr_price;
            $new_goods['total_price']=($goods['price'] + $attr_price) * $v['new_count'];

            $is_exists = false;
            $org_goods = null;
            foreach($org_goods_item as $kk=>$vv){
                if($v['goods_id'] == $vv['goods_id'] && count(array_diff($v['attr_ids'] ?? [], $vv['attr_ids'] ?? [])) == 0){
                    $is_exists = true;
                    $org_goods = $org_goods_item[$k];
                    break;
                }
            }

            if($is_exists && $v['new_count'] != $org_goods['new_count']){
                $new_goods['old_count'] = $org_goods['new_count'];
            }

            $new_goods_item[] = $new_goods;
        }

        //金额计算
        $total_price += $model->delivery_price;

        $model->setAttribute("goods_item",Json::encode($new_goods_item));
        $model->setAttribute("total_price",$total_price);
        $model->setAttribute("real_price",$total_price - $model->coupon_price);
        $model->setAttribute("status",Constants::ORDER_COMPLETE);
        $model->setAttribute("is_adjust",2);
        return $model->update() !== false;
    }
}